{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "https://langchain-ai.github.io/langgraph/how-tos/memory/add-summary-conversation-history"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "d32295d39a229245"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "from langchain_core.messages import SystemMessage, RemoveMessage\n",
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_community.llms.tongyi import Tongyi\n",
    "from dotenv import load_dotenv\n",
    "from typing import Literal\n",
    "\n",
    "from langchain_core.tools import tool\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import MessagesState, StateGraph, START, END\n",
    "from langgraph.prebuilt import ToolNode\n",
    "\n",
    "memory = MemorySaver()\n",
    "\n",
    "# We will add a `summary` attribute (in addition to `messages` key,\n",
    "# which MessagesState already has)\n",
    "class State(MessagesState):\n",
    "    summary: str\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "llm = ChatOpenAI(\n",
    "    openai_api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n",
    "    openai_api_base=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    "    model_name=\"qwen-max\",\n",
    "    temperature=0, \n",
    ")\n",
    "\n",
    "# We now define the logic for determining whether to end or summarize the conversation\n",
    "def should_continue(state: State) -> Literal[\"summarize_conversation\", END]:\n",
    "    \"\"\"Return the next node to execute.\"\"\"\n",
    "    messages = state[\"messages\"]\n",
    "    # If there are more than six messages, then we summarize the conversation\n",
    "    if len(messages) > 6:\n",
    "        return \"summarize_conversation\"\n",
    "    # Otherwise we can just end\n",
    "    return END\n",
    "\n",
    "# Define the logic to call the model\n",
    "def call_model(state: State):\n",
    "    # If a summary exists, we add this in as a system message\n",
    "    summary = state.get(\"summary\", \"\")\n",
    "    if summary:\n",
    "        system_message = f\"Summary of conversation earlier: {summary}\"\n",
    "        messages = [SystemMessage(content=system_message)] + state[\"messages\"]\n",
    "    else:\n",
    "        messages = state[\"messages\"]\n",
    "    response = llm.invoke(messages)\n",
    "    # We return a list, because this will get added to the existing list\n",
    "    return {\"messages\": [response]}\n",
    "\n",
    "def summarize_conversation(state: State):\n",
    "    # First, we summarize the conversation\n",
    "    summary = state.get(\"summary\", \"\")\n",
    "    if summary:\n",
    "        # If a summary already exists, we use a different system prompt\n",
    "        # to summarize it than if one didn't\n",
    "        summary_message = (\n",
    "            f\"This is summary of the conversation to date: {summary}\\n\\n\"\n",
    "            \"Extend the summary by taking into account the new messages above:\"\n",
    "        )\n",
    "    else:\n",
    "        summary_message = \"Create a summary of the conversation above:\"\n",
    "\n",
    "    messages = state[\"messages\"] + [HumanMessage(content=summary_message)]\n",
    "    response = llm.invoke(messages)\n",
    "    # We now need to delete messages that we no longer want to show up\n",
    "    # I will delete all but the last two messages, but you can change this\n",
    "    delete_messages = [RemoveMessage(id=m.id) for m in state[\"messages\"][:-2]]\n",
    "    return {\"summary\": response.content, \"messages\": delete_messages}\n",
    "\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(State)\n",
    "\n",
    "# Define the conversation node and the summarize node\n",
    "workflow.add_node(\"conversation\", call_model)\n",
    "workflow.add_node(summarize_conversation)\n",
    "\n",
    "# Set the entrypoint as conversation\n",
    "workflow.add_edge(START, \"conversation\")\n",
    "\n",
    "# We now add a conditional edge\n",
    "workflow.add_conditional_edges(\n",
    "    # First, we define the start node. We use `conversation`.\n",
    "    # This means these are the edges taken after the `conversation` node is called.\n",
    "    \"conversation\",\n",
    "    # Next, we pass in the function that will determine which node is called next.\n",
    "    should_continue,\n",
    ")\n",
    "\n",
    "# We now add a normal edge from `summarize_conversation` to END.\n",
    "# This means that after `summarize_conversation` is called, we end.\n",
    "workflow.add_edge(\"summarize_conversation\", END)\n",
    "\n",
    "graph = workflow.compile(checkpointer=memory)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:41:09.466850Z",
     "start_time": "2024-12-09T05:41:09.362655Z"
    }
   },
   "id": "edc582d5d0bb15e2",
   "execution_count": 9
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAFNAQIDASIAAhEBAxEB/8QAHQABAAICAwEBAAAAAAAAAAAAAAUGBAcCAwgBCf/EAFUQAAEDBAADAggKBwQGBQ0AAAEAAgMEBQYRBxIhEzEVFyJBVpTR0wgUFjZCUWF0ldIjMlRVcYGyM1KTtCRDcnOhwQklY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iAiIgIiICIiDV+T8EoKqaSpx+sZanu2TRSxc9MTvfkgadHv7CW/U0KpycJMyjcQKa0yjfRzK+TqP5whb8Rezhfq21YVO7e/it82gPFRmX7FbPX3e6TxUZl+xWz193ulv9Fu/etpyjSfM5ZNAeKjMv2K2evu90niozL9itnr7vdLf6J+9bTlGk+ZyyaA8VGZfsVs9fd7pfW8JsycdfFLU0+YvuD9fz1CT/wAFv5E/etpyjT+zlk1FYeBs0srZchuTJIQetDbgWtf9j5XeUR9jQw/brotsUtLDQ00VPTQx09PCwRxxRNDWMaBoNAHQADpoLtReZtG1421TfFqvbQERFxoIiICIiD//2Q==",
      "text/plain": "<IPython.core.display.Image object>"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.core.display import Image\n",
    "\n",
    "display(Image(graph.get_graph().draw_mermaid_png()))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:41:10.326802Z",
     "start_time": "2024-12-09T05:41:09.470573Z"
    }
   },
   "id": "e6b17ea77623de1b",
   "execution_count": 10
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Using the graph\n"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "23a99c8c7c3263e3"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "def print_update(update):\n",
    "    for k, v in update.items():\n",
    "        for m in v[\"messages\"]:\n",
    "            m.pretty_print()\n",
    "        if \"summary\" in v:\n",
    "            print(f\"summary  {k}: {v['summary']}\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:41:10.334779Z",
     "start_time": "2024-12-09T05:41:10.328981Z"
    }
   },
   "id": "72129227034bf473",
   "execution_count": 11
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001B[1m Human Message \u001B[0m=================================\n",
      "\n",
      "hi! I'm bob\n",
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "Hello Bob! It's nice to meet you. How can I assist you today?\n",
      "================================\u001B[1m Human Message \u001B[0m=================================\n",
      "\n",
      "what's my name?\n",
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "Your name is Bob! Is there anything else you'd like to know or discuss?\n",
      "================================\u001B[1m Human Message \u001B[0m=================================\n",
      "\n",
      "i like the celtics!\n",
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "That's great, Bob! The Boston Celtics have a rich history and a passionate fan base. Are you following their current season? Any favorite players or memorable moments you'd like to share?\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "config = {\"configurable\": {\"thread_id\": \"4\"}}\n",
    "input_message = HumanMessage(content=\"hi! I'm bob\")\n",
    "input_message.pretty_print()\n",
    "for event in graph.stream({\"messages\": [input_message]}, config, stream_mode=\"updates\"):\n",
    "    print_update(event)\n",
    "\n",
    "input_message = HumanMessage(content=\"what's my name?\")\n",
    "input_message.pretty_print()\n",
    "for event in graph.stream({\"messages\": [input_message]}, config, stream_mode=\"updates\"):\n",
    "    print_update(event)\n",
    "\n",
    "input_message = HumanMessage(content=\"i like the celtics!\")\n",
    "input_message.pretty_print()\n",
    "for event in graph.stream({\"messages\": [input_message]}, config, stream_mode=\"updates\"):\n",
    "    print_update(event)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:41:15.056588Z",
     "start_time": "2024-12-09T05:41:10.338431Z"
    }
   },
   "id": "7faf260a32c0f51c",
   "execution_count": 12
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "{'messages': [HumanMessage(content=\"hi! I'm bob\", additional_kwargs={}, response_metadata={}, id='1e64add7-9204-4f3b-9c1d-68704f438b8a'),\n  AIMessage(content=\"Hello Bob! It's nice to meet you. How can I assist you today?\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 13, 'total_tokens': 30, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'qwen-max', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-fd95d842-5181-4845-b612-295626fac8cb-0', usage_metadata={'input_tokens': 13, 'output_tokens': 17, 'total_tokens': 30, 'input_token_details': {}, 'output_token_details': {}}),\n  HumanMessage(content=\"what's my name?\", additional_kwargs={}, response_metadata={}, id='bb56e57e-c89d-4904-9a9e-33bb11563e05'),\n  AIMessage(content=\"Your name is Bob! Is there anything else you'd like to know or discuss?\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 45, 'total_tokens': 62, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'qwen-max', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-4ffee9e1-c414-48b3-b8b7-733c5bfa6d04-0', usage_metadata={'input_tokens': 45, 'output_tokens': 17, 'total_tokens': 62, 'input_token_details': {}, 'output_token_details': {}}),\n  HumanMessage(content='i like the celtics!', additional_kwargs={}, response_metadata={}, id='dc909339-9a3c-4c60-ab36-e274989f86ba'),\n  AIMessage(content=\"That's great, Bob! The Boston Celtics have a rich history and a passionate fan base. Are you following their current season? Any favorite players or memorable moments you'd like to share?\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 38, 'prompt_tokens': 79, 'total_tokens': 117, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'qwen-max', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-01755314-4ca5-404b-b6f1-1b9223ee57f7-0', usage_metadata={'input_tokens': 79, 'output_tokens': 38, 'total_tokens': 117, 'input_token_details': {}, 'output_token_details': {}})]}"
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "values = graph.get_state(config).values\n",
    "values"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:41:15.073468Z",
     "start_time": "2024-12-09T05:41:15.060496Z"
    }
   },
   "id": "1d0a90321a5d17c2",
   "execution_count": 13
  },
  {
   "cell_type": "markdown",
   "source": [
    "现在，让我们再发送一条消息"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "950d0defec4be1f3"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001B[1m Human Message \u001B[0m=================================\n",
      "\n",
      "i like how much they win\n",
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "It's always exciting to support a winning team! The Celtics have had some strong seasons and playoff runs in recent years. They have a talented roster and a dedicated coaching staff. Do you have any favorite players on the current team, or are there any upcoming games you're particularly looking forward to?\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "summary  summarize_conversation: Sure! Here's a summary of our conversation:\n",
      "\n",
      "- You introduced yourself as Bob.\n",
      "- You mentioned that you like the Boston Celtics.\n",
      "- You specifically noted that you enjoy how much they win.\n",
      "- We discussed the team's recent strong performances and their talented roster.\n",
      "- I asked if you had any favorite players or upcoming games you were looking forward to.\n",
      "\n",
      "Is there anything else you'd like to add or discuss?\n"
     ]
    }
   ],
   "source": [
    "input_message = HumanMessage(content=\"i like how much they win\")\n",
    "input_message.pretty_print()\n",
    "for event in graph.stream({\"messages\": [input_message]}, config, stream_mode=\"updates\"):\n",
    "    print_update(event)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:41:21.211238Z",
     "start_time": "2024-12-09T05:41:15.076384Z"
    }
   },
   "id": "72c6adcfa193ba6c",
   "execution_count": 14
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "{'messages': [HumanMessage(content='i like how much they win', additional_kwargs={}, response_metadata={}, id='448c1bdc-7cd6-4959-90f0-8632e90dd7c6'),\n  AIMessage(content=\"It's always exciting to support a winning team! The Celtics have had some strong seasons and playoff runs in recent years. They have a talented roster and a dedicated coaching staff. Do you have any favorite players on the current team, or are there any upcoming games you're particularly looking forward to?\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 59, 'prompt_tokens': 133, 'total_tokens': 192, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'qwen-max', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-806d4aa1-b96e-4d62-a357-3ec47351f422-0', usage_metadata={'input_tokens': 133, 'output_tokens': 59, 'total_tokens': 192, 'input_token_details': {}, 'output_token_details': {}})],\n 'summary': \"Sure! Here's a summary of our conversation:\\n\\n- You introduced yourself as Bob.\\n- You mentioned that you like the Boston Celtics.\\n- You specifically noted that you enjoy how much they win.\\n- We discussed the team's recent strong performances and their talented roster.\\n- I asked if you had any favorite players or upcoming games you were looking forward to.\\n\\nIs there anything else you'd like to add or discuss?\"}"
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "values = graph.get_state(config).values\n",
    "values"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:41:21.223275Z",
     "start_time": "2024-12-09T05:41:21.213202Z"
    }
   },
   "id": "ed28c354c521e545",
   "execution_count": 15
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001B[1m Human Message \u001B[0m=================================\n",
      "\n",
      "what's my name?\n",
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "Your name is Bob. Is there anything else you'd like to talk about or any other questions you have?\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "================================\u001B[1m Remove Message \u001B[0m================================\n",
      "\n",
      "\n",
      "summary  summarize_conversation: Certainly! Here's an updated summary of our conversation:\n",
      "\n",
      "- You introduced yourself as Bob.\n",
      "- You mentioned that you like the Boston Celtics and specifically noted that you enjoy how much they win.\n",
      "- We discussed the team's recent strong performances and their talented roster.\n",
      "- I asked if you had any favorite players or upcoming games you were looking forward to.\n",
      "- You asked me what your name was, and I confirmed that your name is Bob.\n",
      "- You asked again, and I confirmed your name once more.\n",
      "\n",
      "Is there anything else you'd like to add or discuss?\n"
     ]
    }
   ],
   "source": [
    "input_message = HumanMessage(content=\"what's my name?\")\n",
    "input_message.pretty_print()\n",
    "for event in graph.stream({\"messages\": [input_message]}, config, stream_mode=\"updates\"):\n",
    "    print_update(event)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:42:10.874269Z",
     "start_time": "2024-12-09T05:42:03.430729Z"
    }
   },
   "id": "9d14f3d13e393285",
   "execution_count": 18
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mKeyboardInterrupt\u001B[0m                         Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[23], line 2\u001B[0m\n\u001B[1;32m      1\u001B[0m res \u001B[38;5;241m=\u001B[39m graph\u001B[38;5;241m.\u001B[39minvoke({\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mmessages\u001B[39m\u001B[38;5;124m\"\u001B[39m: [input_message]}, config, stream_mode\u001B[38;5;241m=\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mupdates\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m----> 2\u001B[0m res\n",
      "File \u001B[0;32m_pydevd_bundle/pydevd_cython_darwin_312_64.pyx:1187\u001B[0m, in \u001B[0;36m_pydevd_bundle.pydevd_cython_darwin_312_64.SafeCallWrapper.__call__\u001B[0;34m()\u001B[0m\n",
      "File \u001B[0;32m_pydevd_bundle/pydevd_cython_darwin_312_64.pyx:627\u001B[0m, in \u001B[0;36m_pydevd_bundle.pydevd_cython_darwin_312_64.PyDBFrame.trace_dispatch\u001B[0;34m()\u001B[0m\n",
      "File \u001B[0;32m_pydevd_bundle/pydevd_cython_darwin_312_64.pyx:937\u001B[0m, in \u001B[0;36m_pydevd_bundle.pydevd_cython_darwin_312_64.PyDBFrame.trace_dispatch\u001B[0;34m()\u001B[0m\n",
      "File \u001B[0;32m_pydevd_bundle/pydevd_cython_darwin_312_64.pyx:928\u001B[0m, in \u001B[0;36m_pydevd_bundle.pydevd_cython_darwin_312_64.PyDBFrame.trace_dispatch\u001B[0;34m()\u001B[0m\n",
      "File \u001B[0;32m_pydevd_bundle/pydevd_cython_darwin_312_64.pyx:585\u001B[0m, in \u001B[0;36m_pydevd_bundle.pydevd_cython_darwin_312_64.PyDBFrame.do_wait_suspend\u001B[0;34m()\u001B[0m\n",
      "File \u001B[0;32m/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py:1184\u001B[0m, in \u001B[0;36mPyDB.do_wait_suspend\u001B[0;34m(self, thread, frame, event, arg, send_suspend_message, is_unhandled_exception)\u001B[0m\n\u001B[1;32m   1181\u001B[0m         from_this_thread\u001B[38;5;241m.\u001B[39mappend(frame_id)\n\u001B[1;32m   1183\u001B[0m \u001B[38;5;28;01mwith\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_threads_suspended_single_notification\u001B[38;5;241m.\u001B[39mnotify_thread_suspended(thread_id, stop_reason):\n\u001B[0;32m-> 1184\u001B[0m     \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_do_wait_suspend(thread, frame, event, arg, suspend_type, from_this_thread)\n",
      "File \u001B[0;32m/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py:1199\u001B[0m, in \u001B[0;36mPyDB._do_wait_suspend\u001B[0;34m(self, thread, frame, event, arg, suspend_type, from_this_thread)\u001B[0m\n\u001B[1;32m   1196\u001B[0m             \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_call_mpl_hook()\n\u001B[1;32m   1198\u001B[0m         \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mprocess_internal_commands()\n\u001B[0;32m-> 1199\u001B[0m         time\u001B[38;5;241m.\u001B[39msleep(\u001B[38;5;241m0.01\u001B[39m)\n\u001B[1;32m   1201\u001B[0m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mcancel_async_evaluation(get_current_thread_id(thread), \u001B[38;5;28mstr\u001B[39m(\u001B[38;5;28mid\u001B[39m(frame)))\n\u001B[1;32m   1203\u001B[0m \u001B[38;5;66;03m# process any stepping instructions\u001B[39;00m\n",
      "\u001B[0;31mKeyboardInterrupt\u001B[0m: "
     ]
    }
   ],
   "source": [
    "res = graph.invoke({\"messages\": [input_message]}, config, stream_mode=\"updates\")\n",
    "res"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-12-09T05:48:16.722231Z",
     "start_time": "2024-12-09T05:45:32.809428Z"
    }
   },
   "id": "bd8e5ebc99b2b40b",
   "execution_count": 23
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
